var express = require('express');
var moment = require("moment");
var orm = require('orm');
var _ = require('underscore');
var Q = require('q');

var log4js = require('log4js');
var logger = log4js.getLogger();

var router = express.Router();

var promisqQueryFindAll = function(model, condition) {
  var deferred = Q.defer();

  logger.info(condition)
  model.find(condition).all(function(err, results) {
    if (err) {
      logger.error(err)
      deferred.reject(err);
    } else {
      deferred.resolve(results);
    }
  });

  return deferred.promise;
}

var getEndOfMonth = function (year, month) {
  var map = {
    '01': 31,
    '02': function (year, month) {
      if (year % 4 == 0) {
        return 29
      }else{
        return 28
      }
    },
    '03': 31,
    '04': 30,
    '05': 31,
    '06': 30,
    '07': 31,
    '08': 31,
    '09': 30,
    '10': 31,
    '11': 30,
    '12': 31
  }

  return _.isFunction(map[month]) ? map[month](year, month) : map[month];
}

var queryDailyForMonth = function (models, st, code) {
  var year = moment(new Date(parseInt(st))).format('YYYY');
  var month = moment(new Date(parseInt(st))).format('MM');
  var endday = getEndOfMonth(year, month);
  return promisqQueryFindAll(models.trade_prt_sale_daily, {
    create_date: orm.between(moment().year(year).month(parseInt(month)-1).date(1).format('YYYY-MM-DD'), moment().year(year).month(parseInt(month)-1).date(endday).format('YYYY-MM-DD')),
    single_code: code
  });
}

var queryDailyForWeek = function(models, st, code) {
  return promisqQueryFindAll(models.trade_prt_sale_daily, {
    create_date: orm.between(moment(new Date(parseInt(st))).isoWeekday("Monday").format('YYYY-MM-DD'), moment(new Date(parseInt(st))).isoWeekday("Sunday").format('YYYY-MM-DD')),
    single_code: code
  });
}

var queryMonth = function (models, st, code) {
  return promisqQueryFindAll(models.trade_prt_sale_monthly, {
    create_month: moment(new Date(parseInt(st))).format('YYYY-MM'),
    single_code: code
  });
}

var queryWeek = function(models, st, code) {
  return promisqQueryFindAll(models.trade_prt_sale_weekly, {
    week_start: moment(new Date(parseInt(st))).isoWeekday("Monday").format('YYYY-MM-DD'),
    week_end: moment(new Date(parseInt(st))).isoWeekday("Sunday").format('YYYY-MM-DD'),
    single_code: code
  });
};

var queryDaily = function (models, st, code) {
  return promisqQueryFindAll(models.trade_prt_sale_daily, {
    create_date: moment(new Date(parseInt(st))).format('YYYY-MM-DD'),
    single_code: code
  });
}

var queryDailyAll = function (models, st) {
  return promisqQueryFindAll(models.trade_prt_sale_daily, {
    create_date: moment(new Date(parseInt(st))).format('YYYY-MM-DD'),
  });
}

router.get('/daily', function (req, res, next) {
  var timestamp = req.query.timestamp || Date.now();

  Q.all([queryDailyAll(req.models, timestamp)]).then(function(result) {
    res.json({
      result: {
        summery: result[0],
        detail: null
      },
      error: 0
    });
  }, function() {
    res.json({
      result: null,
      error: -100
    });
  })
})

router.get('/chart', function(req, res, next) {

  var period = req.query.period;
  var timestamp = req.query.timestamp || Date.now();
  var code = req.query.code;

  var map = {
    'day': function (st) {
      Q.all([queryDaily(req.models, st, code)]).then(function(result) {
        res.json({
          result: {
            summery: result[0],
            detail: null
          },
          error: 0
        });
      }, function() {
        res.json({
          result: null,
          error: -100
        });
      })
    },

    'week': function(st) {

      Q.all([queryDailyForWeek(req.models, st, code), queryWeek(req.models, st, code)]).then(function(result) {
        res.json({
          result: {
            summery: result[1],
            detail: result[0]
          },
          error: 0
        });
      }, function() {
        res.json({
          result: null,
          error: -100
        });
      })
    },

    'month': function (st) {
      Q.all([queryDailyForMonth(req.models, st, code), queryMonth(req.models, st, code)]).then(function(result) {
        res.json({
          result: {
            summery: result[1],
            detail: result[0]
          },
          error: 0
        });
      }, function() {
        res.json({
          result: null,
          error: -100
        });
      })
    }
  };


  var fn = map[period];

  if (_.isFunction(fn)) {
    fn(timestamp);
  } else {
    res.json({
      result: null,
      error: -100
    });
  }

});

module.exports = router;